package cn.gz.sboot21.controller;

import cn.gz.sboot21.entity.User;
import cn.gz.sboot21.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@Controller
public class UserController {
    @RequestMapping("/reg")
    @ResponseBody
    public String reg(User user){
        try {
            Connection conn = DBUtils.getConn(); //获取连接
            String sql = "insert into jt_user values(null,?,?,?,?)"; //编写sql
            PreparedStatement ps = conn.prepareStatement(sql);  //获取传输器对象
            ps.setString(1,user.getUsername()); //设置参数
            ps.setString(2,user.getPassword());
            ps.setString(3,user.getNickname());
            ps.setInt(4,user.getAge());
            ps.executeUpdate();  //执行sal
        }catch (Exception e){
            e.printStackTrace();
        }
        return "注册成功";
    }
    @RequestMapping("/login")
    @ResponseBody
    public String login(User user){
        try {
            Connection conn = DBUtils.getConn();
            String sql = "select password from jt_user where username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ResultSet rs = ps.executeQuery();
            if(rs.next()){//如果为真，则查到了
                String pwd = rs.getString(1);
                if(user.getPassword().equals(pwd)){
                    return "登录成功";
                }else {
                    return "密码错误";
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "查无此人";
    }
}
